package com.egene.tw.fcm;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.egene.tw.api.FcmTokenApi;
import com.egene.tw.dao.UserDao_;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;

/**
 * Created by albert on 2017/11/4.
 */

public class AppFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "AppFirebaseI";

    @Override
    public void onTokenRefresh() {
        Log.d(TAG, "onTokenRefresh: ");
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        registerFcmTokenToAppServer(getApplicationContext());
    }

    public static void registerFcmTokenToAppServer(Context context) {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        String userId = UserDao_.getInstance_(context).getUser().getUserID();
        if(!TextUtils.isEmpty(refreshedToken) && !TextUtils.isEmpty(userId)){
            FcmTokenApi.registerFcmToken(userId, refreshedToken, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    Log.d(TAG, "onSuccess: " + statusCode);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.d(TAG, "onFailure: ");
                }
            });
        }
    }
}
